package org.dromara.netbar.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import org.dromara.common.core.utils.AssertUtils;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.netbar.domain.NetbarGiftPackItem;
import org.dromara.netbar.domain.NetbarGiftPackLog;
import org.dromara.netbar.domain.bo.NetbarGiftPackItemBo;
import org.dromara.netbar.domain.vo.*;
import org.dromara.netbar.mapper.NetbarAutoGrantMapper;
import org.dromara.netbar.mapper.NetbarGiftPackLogMapper;
import org.dromara.netbar.service.INetbarCouponService;
import org.dromara.netbar.service.INetbarGiftPackItemService;
import org.springframework.stereotype.Service;
import org.dromara.netbar.domain.bo.NetbarGiftPackBo;
import org.dromara.netbar.domain.NetbarGiftPack;
import org.dromara.netbar.mapper.NetbarGiftPackMapper;
import org.dromara.netbar.service.INetbarGiftPackService;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * 礼包管理Service业务层处理
 *
 * @author Lion Li
 * @date 2025-07-10
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class NetbarGiftPackServiceImpl implements INetbarGiftPackService {

    private final NetbarGiftPackMapper baseMapper;
    private final NetbarAutoGrantMapper autoGrantMapper;
    private final NetbarGiftPackLogMapper giftPackLogMapper;
    private final INetbarCouponService netbarCouponService;
    private final INetbarGiftPackItemService netbarGiftPackItemService;
    /**
     * 查询礼包管理
     *
     * @param packId 主键
     * @return 礼包管理
     */
    @Override
    public NetbarGiftPackVo queryById(Long packId){
        return baseMapper.selectVoById(packId);
    }

    /**
     * 分页查询礼包管理列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 礼包管理分页列表
     */
    @Override
    public TableDataInfo<NetbarGiftPackVo> queryPageList(NetbarGiftPackBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<NetbarGiftPack> lqw = buildQueryWrapper(bo);
        Page<NetbarGiftPackVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        if (CollectionUtil.isNotEmpty(result.getRecords())) {
            // 获取id，根据id获取子项，再循环载入
            List<Long> ids = result.getRecords().stream().map(NetbarGiftPackVo::getPackId).toList();
            List<NetbarGiftPackItemVo> netbarGiftPackItemVos = netbarGiftPackItemService.queryListByPackIds(ids);
            for (NetbarGiftPackVo record : result.getRecords()) {
                record.setGiftPackItemList(netbarGiftPackItemVos.stream().filter(item -> item.getPackId().equals(record.getPackId())).toList());
            }
        }
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的礼包管理列表
     *
     * @param bo 查询条件
     * @return 礼包管理列表
     */
    @Override
    public List<NetbarGiftPackVo> queryList(NetbarGiftPackBo bo) {
        LambdaQueryWrapper<NetbarGiftPack> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<NetbarGiftPack> buildQueryWrapper(NetbarGiftPackBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<NetbarGiftPack> lqw = Wrappers.lambdaQuery();
        lqw.orderByAsc(NetbarGiftPack::getPackId);
        lqw.like(StringUtils.isNotBlank(bo.getPackName()), NetbarGiftPack::getPackName, bo.getPackName());
        return lqw;
    }

    /**
     * 新增礼包管理
     *
     * @param bo 礼包管理
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(NetbarGiftPackBo bo) {
        validEntityBeforeSave(bo);
        NetbarGiftPack add = MapstructUtils.convert(bo, NetbarGiftPack.class);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setPackId(add.getPackId());
            // 添加礼包内卡劵
            for (NetbarGiftPackItemBo item : bo.getGiftPackItemList()) {
                item.setPackId(add.getPackId());
                netbarGiftPackItemService.insertByBo(item);
            }
        }
        return flag;
    }

    /**
     * 修改礼包管理
     *
     * @param bo 礼包管理
     * @return 是否修改成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateByBo(NetbarGiftPackBo bo) {
        validEntityBeforeSave(bo);
        AssertUtils.notNull(bo.getPackId(), "未找到礼包信息不能为空");
        NetbarGiftPack update = MapstructUtils.convert(bo, NetbarGiftPack.class);
        // 先删除, 重新添加
        netbarGiftPackItemService.deleteByPackId(bo.getPackId());
        for (NetbarGiftPackItemBo item : bo.getGiftPackItemList()) {
            item.setPackId(bo.getPackId());
            netbarGiftPackItemService.insertByBo(item);
        }
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(NetbarGiftPackBo entity){
        //TODO 做一些数据校验,如唯一约束
        List<NetbarCouponVo> netbarCouponVos = netbarCouponService.listCouponNameAndId();
        AssertUtils.notNull(entity.getPackName(), "请输入礼包名称");
        AssertUtils.notNull(entity.getPurchaseAmount(), "请输入礼包购买金额");
        AssertUtils.hasSize(entity.getGiftPackItemList(), "请选择礼包内卡劵");
        for (NetbarGiftPackItemBo item : entity.getGiftPackItemList()) {
            AssertUtils.notNull(item.getCouponId(), "请选择礼包内卡劵");
            AssertUtils.notNull(item.getCouponCount(), "请选择礼包内卡劵数量");
            Optional<NetbarCouponVo> couponFirst = netbarCouponVos.stream().filter(c -> c.getCouponId().equals(item.getCouponId())).findFirst();
            AssertUtils.isTrue(couponFirst.isPresent(), "礼包内卡劵不存在");
        }
    }

    /**
     * 校验并批量删除礼包管理信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteByIds(ids) > 0;
    }

    @Override
    public List<NetbarGiftPackVo> listPackNameAndId() {
        List<NetbarGiftPackVo> netbarGiftPackVos = queryList(new NetbarGiftPackBo());
        List<Long> ids = netbarGiftPackVos.stream().map(NetbarGiftPackVo::getPackId).toList();
        List<NetbarGiftPackItemVo> netbarGiftPackItemVos = netbarGiftPackItemService.queryListByPackIds(ids);
        for (NetbarGiftPackVo record : netbarGiftPackVos) {
            record.setGiftPackItemList(netbarGiftPackItemVos.stream().filter(item -> item.getPackId().equals(record.getPackId())).toList());
            if (record.getGiftPackItemList().stream().anyMatch(item -> item.getCouponStatus().equals("过期"))) {
                record.setIsExpired(true);
            }
        }
        return netbarGiftPackVos;
    }

}
